var fs = require('fs');
var getPixels = require("get-pixels")

pngto16bitUtils={};

con_hight_first=0


function get16Color(b,g,r){
    v=(b>>3)+((r>>3)<<11)+((g>>2)<<5)
    return v;
}

pngto16bitUtils.run=async (file,isWriteFile)=>{
    return new Promise(((resolve, reject) => {
        getPixels(file+".png", function(err, img) {
            if(err) {
                console.log("Bad image path")
                return
            }
            s=0
            buffer=[]
            img_row=0;
            img_col=0;
            [img_row,img_col]=[img.shape[1],img.shape[0]]
            inx=0;
            for (let x=0;x<img_col;x++) {
                for (let y = 0; y < img_row; y++) {
                    let [r, g, b] = [img.get(x, y, 0), img.get(x, y, 1), img.get(x, y, 2)];
                    v = get16Color(b, g, r);
                    h = (v & 0xff)
                    l = (v & 0xff00) >> 8
                    if (con_hight_first) {
                        buffer[inx++]=h;
                        buffer[inx++]=l;
                    } else {
                        buffer[inx++]=l;
                        buffer[inx++]=h;
                    }
                }
            }
            resolve(buffer);
            if(isWriteFile){
                fs.writeFileSync(file+".bin", new Buffer(buffer));
            }
        })
    }))
}


module.exports=pngto16bitUtils
